package cn.tpshion.vm.base.interceptor;

import cn.tpshion.vm.common.constant.BaseConstant;
import cn.tpshion.vm.common.constant.InterceptOrder;
import cn.tpshion.vm.common.model.RequestContext;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Objects;

@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor, Ordered {

    @Override
    public int getOrder() {
        return InterceptOrder.REQUEST_INTERCEPTOR.getOrder();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute(BaseConstant.START_TIME, System.currentTimeMillis());
        log.info("Request url:{}", request.getServletPath());
        log.info("queryParam:{}", JSON.toJSONString(request.getParameterMap()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        RequestContext.clear();
        Long startTime = (Long) request.getAttribute(BaseConstant.START_TIME);
        if(Objects.nonNull(startTime)){
            log.info("url:{} cost:{}ms", request.getServletPath(), System.currentTimeMillis() - startTime);
        }
    }
}
